package Extra;

// TCPEchoClient
// send Message to Server , Received OK Message

import java.net.InetAddress ;
import java.net.UnknownHostException ;
import java.net.Socket ;
import java.io.PrintWriter ;
import java.util.Scanner ;
import java.io.IOException ;

public class TCPEchoClient 
{
   private static final int PORT = 5000 ;
   private static Socket socket ;
   private static InetAddress address ;
   
   public static void main (String args[])
   {
      try
      {
         address = InetAddress.getLocalHost();
      }
      catch (UnknownHostException e)
      {
         System.out.println("Cannot Find IP Number !");
      }
      
      accessServer();
   }
   
   public static void accessServer ()
   {
      try
      {
         socket = new Socket(address,PORT);
         
         Scanner input = new Scanner( socket.getInputStream() );
         PrintWriter output = new PrintWriter( socket.getOutputStream() , true );
         
         String msgIn = "" , msgOut = "";
         
         Scanner uInput = new Scanner( System.in);
         
         while ( ! msgOut.equals("CLOSE") ) 
         {
            System.out.print("Enter Message : " );
            msgOut = uInput.nextLine();
            
            output.println(msgOut);
            
            if ( !msgOut.equals("CLOSE")) 
            {
               msgIn = input.nextLine();   
               System.out.println("Server  > " + msgIn );
            }
         } 
         
      }
      catch ( IOException e)
      {   e.printStackTrace()   ;}
      
      finally
      {
         try
         {
            if ( socket != null )
               socket.close();
            
            System.out.println("Clinet Close Connection !");
         }
         catch ( IOException e)
         {
            System.out.println("Cannot Disconnect Client !");
            System.exit(1);
         }
      }
   }
}